<template>
    <div>
        <el-row>
            <el-tabs v-loading="isLoading" v-model="typeActiveTab" type="card" @tab-click="handleTabClick">
                <el-tab-pane label="基本信息" name="tabBase" v-if="!isLoading">
                    <base-info ref="baseInfoForm" :isAdvancedSetting="isAdvancedSetting" :diagnosis="diagnosis"></base-info>

                    <el-row type="flex" justify="center" style="margin-top: 20px">
                        <el-button @click="diagnosisDialogSave" type="primary" size="mini">
                            保存
                        </el-button>
                        <el-button @click="goBack" size="mini">
                            返回
                        </el-button>
                    </el-row>
                </el-tab-pane>
                <el-tab-pane label="病理信息" name="tabPathologyInfo" v-if="!isLoading">
                    <pathology-info :diagnosis="diagnosis"></pathology-info>

                    <!-- <el-row
                        type="flex"
                        justify="center"
                        style="margin-top: 20px"
                    >
                        <el-button
                            @click="diagnosisDialogSave"
                            type="primary"
                            size="mini"
                        >
                            保存
                        </el-button>
                    </el-row> -->
                </el-tab-pane>
                <el-tab-pane label="病理切片" name="tabPathologyList" v-if="!isLoading">
                    <span slot="label">病理切片
                        <el-badge v-if="diagnosis.biopsyList.length > 0" :value="diagnosis.biopsyList.length"
                            class="tab-content-badge"></el-badge>
                    </span>
                    <pathology-list :diagnosis="diagnosis"></pathology-list>
                </el-tab-pane>
                <el-tab-pane label="诊断意见" name="tabOpinion" v-if="!isLoading">
                    <opinion :diagnosis="diagnosis" ref="diagnosisDetailOpinion" :annotations="diagnosis.annotationsList"
                        @diagnosisRequest="diagnosisRequest" @diagnosisSearch="diagnosisSearch"></opinion>
                </el-tab-pane>
                <el-tab-pane label="历史报告" name="historicalReport" v-if="!isLoading">
                    <span slot="label">历史报告
                        <el-badge v-if="historyReportCount > 0" :value="historyReportCount"
                            class="tab-content-badge"></el-badge>
                    </span>
                    <historicalReport :diagnosis="diagnosis" :listArry="listArry" />
                </el-tab-pane>
                <el-tab-pane label="附件资料" name="tabAttachment" v-if="!isLoading">
                    <attachment :data="diagnosis.attachment" :diagnosis-id="diagnosis.id"></attachment>
                </el-tab-pane>
                <el-tab-pane label="讨论留言" name="tabDiscussion" v-if="!isLoading">
                    <discussion :messageList="diagnosis.messageBoardList" :isTheseDoctor="isTheseDoctor"
                        :diagnosis="diagnosis"></discussion>
                </el-tab-pane>

                <el-tab-pane label="分子病理" name="tabMolecularPathology" v-if="!isLoading">
                </el-tab-pane>
                <el-tab-pane label="检验报告" name="tabInspectionReport" v-if="!isLoading">
                    <span slot="label">检验报告
                        <el-badge v-if="inspectionReportCount > 0" :value="inspectionReportCount"
                            class="tab-content-badge"></el-badge>
                    </span>
                    <opinion-bottom :diagnosis="diagnosis" ref="bottom" @drawECharts="getPicData"></opinion-bottom>
                </el-tab-pane>
                <el-tab-pane label="胃镜报告" name="tabGastroscopeReport" v-if="!isLoading">
                    <span slot="label">胃镜报告
                        <el-badge v-if="gastroscopeReportList.length > 0" :value="gastroscopeReportList.length"
                            class="tab-content-badge"></el-badge>
                    </span>
                    <gastroscope-report :gastroscopeReportList="gastroscopeReportList"></gastroscope-report>
                </el-tab-pane>
                <el-tab-pane label="检查报告" name="tabCheckReport" v-if="!isLoading">

                </el-tab-pane>
                <el-tab-pane label="电子病历" name="tabElectronicMedical" v-if="!isLoading">
                    <span slot="label">电子病历
                        <el-badge v-if="electronicMedicalCount > 0" :value="electronicMedicalCount"
                            class="tab-content-badge"></el-badge>
                    </span>
                    <electronic-medical :electronicMedicalData="electronicMedicalData"
                        :activeName="activeDiagnosisDetailElectronicMedicalName"></electronic-medical>
                </el-tab-pane>
                <el-tab-pane label="诊断依据" name="diagnosticBasis" v-if="!isLoading">
                    <diagnostic-basis :content="diagnosticBasisData.data"
                        :our-conclusion="diagnosticBasisData.ourConclusion" :table-data="diagnosticBasisData.tableData"
                        :name="diagnosticBasisData.name" :sex="diagnosticBasisData.sex" :age="diagnosticBasisData.age"
                        :height="diagnosticBasisData.height" :weight="diagnosticBasisData.weight"
                        :suspicious="diagnosticBasisData.suspicious" />
                </el-tab-pane>
            </el-tabs>
        </el-row>
        <el-dialog :close-on-click-modal="false" title="检验指标趋势图" :visible.sync="PICdialogVisible" width="80%">
            <el-form :model="picForm" :inline="true">
                <el-form-item label="选择检验项">
                    <el-select v-model="PicSelectionItemsData" placeholder="选择检验项" size="mini" clearable
                        @change="PicSelectionItemschange">
                        <el-option v-for="item in SelectionItemsData" :key="item.value" :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div id="examLevel" style="height: 300px"></div>
            <span slot="footer" class="dialog-footer">
                <el-button size="mini" type="primary" @click="PICdialogVisible = false">关 闭</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import _ from 'lodash';
import diagnosisDefaultBase from '@templates/diagnosisDefault';
import Client from '../../../server/client';
import BaseInfo from '@/client/templates/components/DiagnosisMatchDetailBase';
import PathologyInfo from '@/client/templates/components/DiagnosisMatchDetailPathologyInfo';
import PathologyList from '@/client/templates/components/DiagnosisDetailPathologyList';
import Opinion from '@/client/templates/components/DiagnosisDetailOpinion';
import Attachment from '@/client/templates/components/DiagnosisDetailAttachment';
import GastroscopeReport from '@/client/templates/components/DiagnosisDetailGastroscopeReport';
import ElectronicMedical from '@/client/templates/components/DiagnosisDetailElectronicMedical';
import DiagnosticBasis from '@/client/templates/components/DiagnosticBasis';
import OpinionBottom from '@/client/templates/components/OpinionBottom.vue';
import Discussion from '@/client/templates/components/diagnosisDetailDiscussion';
import historicalReport from '@/client/templates/components/DiagnosisDetailhistoricalReport';

import moment from 'moment';
const echarts = require('echarts');
const changeKeyListDefault = [
    'freezeType', //冰冻
    'subspecialtyType', //诊断组
    'hisnumber', //病人his码
    'marryType', //婚姻
    'nationalType', //民族
    'occupation', //职业
    'patientAddress', //病人地址
    'PatientNo', //门诊号
    'outpatientDepartment', //门诊科室
    'hospitalizedNo', //住院号
    'patientPhone', //病人电话
    'applicationNo', //申请单号
    'caseLibrary', //病例库
    'expenseCategory', //病人费别
    'chargingSituation', //收费情况
    'operationTime', //手术时间
    'operationName', //手术名称
    'isMenopauseType', //是否绝经
    'menopauseTime', //末次绝经时间

    'patientId',
    'checkCategory',
    'patientCategory',
    'name',
    'age',
    'ageUnit',
    'cardId',
    'wardName',
    'bedId',
    'sampleBody',
    'sampleOrganId',
    'sendDoctor',
    'sendDepartment',
    'sendDoctorTel',
    'specimenName',
    'specimenType',
    'specimenRegisterTime',

    'needFirstVisit',
    'needSkipSubmit',
    'canFinalVerify',

    'pathologySummary',
    'pathologyClinicalDiagnosis',
    'pathologyObserved',
    'pathologyDiagnosis',
    'pathologyMolecular',
    'pathologyImmunology',
];

const diagnosisDefault = _.clone(diagnosisDefaultBase);
diagnosisDefault.previousPathologyId = '';
diagnosisDefault.nextPathologyId = '';
diagnosisDefault.collectionId = 0;

export default {
    name: 'shareIndex',
    props: ['ActiveTab'],
    components: {
        BaseInfo,
        PathologyInfo,
        PathologyList,
        Opinion,
        Attachment,
        Discussion,
        GastroscopeReport,
        OpinionBottom,
        ElectronicMedical,
        DiagnosticBasis,
        historicalReport,
    },

    data() {
        return {
            activeDiagnosisDetailElectronicMedicalName: 'medicalRecords',
            imageServiceURL: process.env.ImageServiceURL,
            diagnosis: diagnosisDefault,
            diagnosisClone: diagnosisDefault,
            changeKeyList: changeKeyListDefault,
            typeActiveTab: 'tabOpinion',
            isLoading: true,
            diagnosisIdBak: '',
            pathologyIdBak: '',
            isAdvancedSetting: false,

            wbClient: null,
            collectionDignosis: null,
            collectionAnnotationImages: null,

            currentAnnotationImages: [],
            gastroscopeReportList: [],
            electronicMedicalData: {},
            diagnosticBasisData: {
                showStatus: false,
                data: null,
                ourConclusion: '',
                tableData: [],
                name: '',
                sex: '',
                age: '',
                height: '',
                weight: '',
                suspicious: '高度可疑',
            },
            electronicMedicalCount: 0,
            inspectionReportCount: 0,
            historyReportCount: 0,
            listArry: [],
            // 趋势图弹窗
            PICdialogVisible: false,
            PicSelectionItemsData: [],
            SelectionItemsData: [],
            picForm: {},
        };
    },

    async mounted() {
        this.wbClient = new Client(process.env.WEBSORKET_URL);
        this.collectionDignosis = this.wbClient.subscribe('diagnosis');
        this.collectionAnnotationImages =
            this.wbClient.subscribe('annotations');
        const { state } = this.$store;
        this.collectionDignosis.addObserve(state.user.id, (data) => {
            console.log('observe', 'diagnosis', state.user.id, data);
            if (this.pathologyIdBak !== data.diagnosisId) {
                this.$store.commit('setPropertyGeneral', {
                    key: 'diagnosis',
                    value: {
                        pathologyId: data.diagnosisId,
                        pDiagnosisType: state.diagnosis.pDiagnosisType,
                    },
                });
                this.pathologyIdBak = data.diagnosisId;
                sessionStorage.setItem('pathologyId', data.diagnosisId);
                this.diagnosisRequest();
            }
        });
        this.collectionAnnotationImages.addObserve(state.user.id, (data) => {
            console.log(
                'observe',
                'collectionAnnotationImages',
                state.user.id,
                data
            );

            const waitToAdd = [];
            data.annotationsData.forEach((anno) => {
                const { imageUrl } = anno;
                let find = false;
                for (
                    let i = 0;
                    i < this.diagnosis.annotationsList.length;
                    i++
                ) {
                    if (
                        this.diagnosis.annotationsList[i].imageUrl === imageUrl
                    ) {
                        find = true;
                        waitToAdd.push(this.diagnosis.annotationsList[i]);
                        break;
                    }
                }

                if (!find) {
                    waitToAdd.push({
                        imageUrl,
                        userId: anno.saveUser,
                    });
                }
            });
            this.diagnosis.annotationsList = [];
            waitToAdd.forEach((item) => {
                this.diagnosis.annotationsList.push(item);
            });
            if (this.$refs && this.$refs.diagnosisDetailOpinion) {
                this.$refs.diagnosisDetailOpinion.annotationChange();
            }
        });
        await this.diagnosisRequest();
    },
    destroyed() {
        console.log('destroyed');
        this.wbClient.close();
    },
    computed: {
        doctorList() {
            const list = [];
            this.diagnosis.diagnosisDetailList.forEach((t) => {
                list.push({
                    id: t.doctorId,
                    level: t.currentLevel,
                    name: t.doctorName,
                });
            });
            return list;
        },
        userId() {
            return this.$store.state.user.id;
        },
        isTheseDoctor() {
            return this.doctorList.some((t) => t.id === this.userId);
        },
    },
    methods: {
        getHistoryList() {
            const pathologyId = sessionStorage.getItem('pathologyId');

            this.$axios({
                method: 'GET',
                url: `/PROXY-Remote/historyReport/getAll/by/${pathologyId}`,
            }).then((res) => {
                if (res.data.code === 200) {
                    this.listArry = res.data.data;
                    this.historyReportCount = this.listArry.length;
                }
            });
        },
        handleTabClick() {
            if (this.typeActiveTab === 'tabGastroscopeReport') {
                this.getGastroscopeReportList();
            } else if (this.typeActiveTab === 'tabElectronicMedical') {
                this.getElectronicMedical();
            }
        },
        getInspectionReportCount() {
            const pathologyId = sessionStorage.getItem('pathologyId');
            this.$axios({
                method: 'GET',
                url: `/PROXY-Remote/inspectionInformation/special-index?page=1&pathologyId=${pathologyId}&size=10&specialIndicators=0`,
            }).then((res) => {
                if (res && res.data.code === 200) {
                    this.inspectionReportCount = res.data.count;
                }
            });
        },
        getGastroscopeReportList() {
            const pathologyId = sessionStorage.getItem('pathologyId');
            this.$axios({
                method: 'GET',
                url: `/PROXY-Remote/gastroscopy_electronic_report/getAll/by/${pathologyId}`,
            }).then((res) => {
                if (res && res.data.code === 200) {
                    let result = res.data.data;
                    this.gastroscopeReportList = result;
                } else {
                    this.gastroscopeReportList = [];
                }
            });
        },
        getElectronicMedical() {
            const pathologyId = sessionStorage.getItem('pathologyId');
            this.$axios({
                method: 'GET',
                url: `/PROXY-Remote/outpatientWithHospital/getAll/by/${pathologyId}`,
            }).then((res) => {
                if (res && res.data.code === 200) {
                    this.electronicMedicalData = res.data;
                    this.electronicMedicalCount =
                        res.data.hospital.length + res.data.outpatient.length;
                    if (
                        res.data.hospital.length !== 0 &&
                        res.data.outpatient.length === 0
                    ) {
                        this.activeDiagnosisDetailElectronicMedicalName =
                            'admissionRecord';
                        this.getNLPDiagnosis(
                            this.electronicMedicalData.hospital[0].id
                        );
                    } else {
                        this.activeDiagnosisDetailElectronicMedicalName =
                            'medicalRecords';
                        this.getNLPDiagnosis(
                            this.electronicMedicalData.outpatient[0].id
                        );
                    }
                } else {
                    this.electronicMedicalData = [];
                    this.electronicMedicalCount = 0;
                }
            });
        },
        getNLPDiagnosis(pId) {
            this.$axios({
                method: 'GET',
                //url: `/PROXY-Remote/diagnosticBasis/get/by/0761531b293d973edbaf8eb7e6941793/${pathologyId}`,
                url: `/PROXY-Remote/diagnosticBasis/test/get/by/${pId}`,
            }).then((res) => {
                if (res && res.data.code === 200) {
                    if (res.data.data) {
                        let labelData = {};
                        Object.keys(this.diagnosticBasisData).forEach(
                            (item) => {
                                if (item !== 'showStatus') {
                                    this.diagnosticBasisData[item] =
                                        res.data.data[item];
                                }
                            }
                        );
                        Object.keys(res.data.data).forEach((item) => {
                            const labelItem = item.split('label');
                            if (labelItem.length === 2) {
                                labelData[labelItem[1]] = parseInt(
                                    res.data.data[item]
                                );
                            }
                        });
                        this.diagnosticBasisData.data = labelData;
                        this.diagnosticBasisData.ourConclusion =
                            res.data.data.conclusions;
                    }
                }
            });
        },
        getPatientTableInfo() {
            const that = this;
            this.$axios({
                method: 'GET',
                url: '/PROXY-Remote/inspectionInformation/get/by/organId',
                params: {
                    page: 1,
                    size: 200,
                },
            }).then(function (res) {
                if (res.data.code !== 200) {
                    throw new Error(res.data);
                } else {
                    that.diagnosticBasisData.tableData = res.data.data;
                }
            });
        },
        updateDiagnoseCollection(diagnosisId) {
            const { state } = this.$store;
            this.collectionDignosis.addOrUpdate(
                state.user.id,
                {
                    diagnosisId,
                },
                true
            );
        },
        async diagnosisRequest() {
            const pDiagnosisUuid = this.$route.params.diagnosisUuid;
            console.log('happened-diagnosisRequest');
            this.isLoading = true;
            const pDiagnosisType = sessionStorage.getItem('pDiagnosisType');
            const pathologyId = sessionStorage.getItem('pathologyId');
            let res = '';

            try {
                res = await this.$axios({
                    method: 'GET',
                    url: `/PROXY-Remote/diagnosis/getDiagnosisInformation/by/${pDiagnosisUuid}`,
                });
                console.log('res', res);
                if (res && res.data.code !== 200) {
                    this.$message.warning('未找到该诊断');
                    this.isLoading = false;
                } else {
                    //获取检验报告角标
                    this.getInspectionReportCount();
                    //获取胃镜报告信息列表
                    this.getGastroscopeReportList();
                    //获取电子病历信息列表
                    this.getElectronicMedical();
                    //获取历史报告角标
                    this.getHistoryList();
                    this.isLoading = true;
                    const result = res.data.data;
                    // 更新 id 和病理编号的备份
                    this.diagnosisIdBak = result.id;
                    this.pathologyIdBak = pathologyId;
                    this.$store.commit('setPropertyGeneral', {
                        key: 'diagnosis',
                        value: {
                            id: result.id,
                            pathologyId,
                        },
                    });

                    Object.keys(this.diagnosis).forEach((key) => {
                        if (typeof this.diagnosis[key] === 'string') {
                            this.diagnosis[key] = _.get(result, key, '');
                        } else if (typeof this.diagnosis[key] === 'number') {
                            this.diagnosis[key] = _.get(result, key, 0);
                        } else if (this.diagnosis[key] instanceof Array) {
                            this.diagnosis[key] = _.clone(result[key]);
                        } else if (this.diagnosis[key] instanceof Object) {
                            this.diagnosis[key] = _.get(result, key, {
                                name: '',
                            });
                        } else {
                            this.diagnosis[key] = _.get(result, key, '');
                        }
                        this.diagnosis.attachment = result.attachmentList;
                        if (this.diagnosis[key] === null) {
                            this.diagnosis[key] = '';
                        }
                    });
                    this.diagnosis.checkCategory = result.checkCategory;
                    // 取材脏器名字获取
                    this.diagnosis.sampleOrganName = _.get(
                        this.diagnosis.sampleOrganOrgan,
                        'name',
                        ''
                    );
                    this.diagnosis.ageAll = `${this.diagnosis.age}${this.diagnosis.ageUnitName}`;
                    this.diagnosis.diagnosisDetailList.forEach((t, index) => {
                        if (t.detailString) {
                            const detailString = t.detailString.replace(
                                '\\',
                                ''
                            );
                            this.diagnosis.diagnosisDetailList[
                                index
                            ].detailJson = JSON.parse(detailString);
                        } else {
                            this.diagnosis.diagnosisDetailList[
                                index
                            ].detailJson = {};
                        }
                    });
                    // 初始化标注数据
                    this.diagnosis.annotationsList = [];
                    this.diagnosis.biopsyList.forEach((biopsy) => {
                        if (biopsy.annotationsList) {
                            biopsy.annotationsList.forEach((item) => {
                                this.diagnosis.annotationsList.push({
                                    id: item.id,
                                    userId: item.createUserId,
                                    imageUrl:
                                        this.imageServiceURL + item.imageUrl,
                                });
                            });
                        }
                    });
                    //先兼容一下切片标签  后期要换接口
                    this.diagnosis.sliceLabel = '';
                    this.diagnosis.biopsyList.forEach((biopsy) => {
                        if (!!biopsy.sliceLabel) {
                            this.diagnosis.sliceLabel +=
                                biopsy.sliceLabel + ' 、';
                        }
                    });
                    // 调用副本
                    this.diagnosisClone = _.clone(this.diagnosis);
                    this.isLoading = false;

                    // 同步病理id
                    this.updateDiagnoseCollection(pathologyId);
                }
            } catch (e) {
                console.log('happened');
                this.$message.warning('请求失败');
                this.isLoading = false;
            }
        },

        diagnosisSearch(pathologyIdParams) {
            const pDiagnosisType = sessionStorage.getItem('pDiagnosisType');
            const pathologyId = sessionStorage.setItem(
                'pathologyId',
                pathologyIdParams
            );
            this.$store.commit('setPropertyGeneral', {
                key: 'diagnosis',
                value: {
                    pathologyId,
                    pDiagnosisType: pDiagnosisType,
                },
            });
            this.diagnosisRequest();
        },
        async diagnosisDialogSave() {
            this.$refs.baseInfoForm
                .validateForm()
                .then(async () => {
                    // 保留变更的字段，去除未修改的字段
                    // 对于三个诊断设置字段，修改脏器时会默认更新这些字段，若手动变更了该值则以手动设置的值为准
                    const diagnosisTemp = {
                        id: this.diagnosis.id,
                    };
                    this.changeKeyList.forEach((key) => {
                        if (this.diagnosisClone[key] !== this.diagnosis[key]) {
                            diagnosisTemp[key] = this.diagnosis[key];
                        }
                    });
                    // 诊断三项高级设置处理
                    if (!this.isAdvancedSetting) {
                        delete diagnosisTemp.needFirstVisit;
                        delete diagnosisTemp.needSkipSubmit;
                        delete diagnosisTemp.canFinalVerify;
                    } else {
                        diagnosisTemp.needFirstVisit =
                            this.diagnosis.needFirstVisit;
                        diagnosisTemp.needSkipSubmit =
                            this.diagnosis.needSkipSubmit;
                        diagnosisTemp.canFinalVerify =
                            this.diagnosis.canFinalVerify;
                    }
                    diagnosisTemp.cardId = this.diagnosis.cardId;
                    const res = await this.$axios({
                        method: 'PUT',
                        url: `/PROXY-Remote/diagnosis/${diagnosisTemp.id}`,
                        data: diagnosisTemp,
                    });

                    if (res && res.data.code === 200) {
                        // 为确保数据一致性与其他标签页不变动，仅复制到Clone
                        this.diagnosisClone = _.clone(this.diagnosis);
                        this.$message.success('保存成功');
                        this.$router.go(0);
                    } else if (res.data.code === 409) {
                        this.$message.info(res.data.message);
                    }
                })
                .catch(() => {
                    this.$message.warning('请填写正确的信息');
                });
        },
        goBack() {
            this.$router.go(-1);
        },
        // 渲染趋势图
        getPicData(row, unit, picVisible, filterData) {
            const pathologyId = sessionStorage.getItem('pathologyId');
            //const filter = { eventNames: row };
            this.SelectionItemsData = filterData;
            this.PICdialogVisible = picVisible;
            this.PicSelectionItemsData = row;
            let result;
            // let url = `/PROXY-aiSearch/lis/special-index?page=1&patientId=${this.diagnosis.patientId}&size=1000`;
            // const datas = [];
            // const params = {};
            // if (filter.ycts) {
            //     params.ycts = encodeURIComponent(filter.ycts);
            // }
            // if (filter.eventNames) {
            //     params.eventNames = encodeURIComponent(filter.eventNames);
            // }
            // Object.getOwnPropertyNames(params).forEach((key) => {
            //     const value = params[key];
            //     if (value) {
            //         datas.push(`${key}=${value}`);
            //     }
            // });
            // if (datas.length > 0) {
            //     url = `${url}&${datas.join('&')}`;
            // }
            // console.log('get-getPicData', url);
            this.$axios({
                // 详见 axios 请求配置项
                method: 'GET',
                url: `/PROXY-Remote/inspectionInformation/get/by/${pathologyId}/${row}`,
            }).then((res) => {
                // 请求失败
                if (res.data.code !== 200) {
                    throw new Error(res.data);
                }
                result = res.data.data;
                console.log('result-getPicData', result);
                this.drawChart(result, row, unit);
                // 请求成功
            });

            return result;
        },
        PicSelectionItemschange() {
            const pathologyId = sessionStorage.getItem('pathologyId');
            this.$axios({
                // 详见 axios 请求配置项
                method: 'GET',
                url: `/PROXY-Remote/inspectionInformation/get/by/${pathologyId}/${this.PicSelectionItemsData}`,
            }).then((res) => {
                if (res.data.code === 200) {
                    // 请求成功
                    this.drawChart(res.data.data, this.PicSelectionItemsData);
                } else {
                    // 请求失败
                    throw new Error(res.data);
                }
            });
        },
        drawChart(result, row, unit) {
            // 基于准备好的dom，初始化echarts实例
            if (result) {
                const xAxisData = [];
                const seriesData = [];
                // 对日期进行排序
                const tempData = result.sort((a, b) =>
                    a.consequence_time > b.consequence_time ? 1 : -1
                );
                tempData.forEach((a) => {
                    xAxisData.push(
                        moment(a.consequence_time).format('YYYY/MM/DD')
                    );
                    seriesData.push(a.consequence);
                })
                // for (const a of tempData) {
                //     xAxisData.push(
                //         moment(a.consequence_time).format('YYYY/MM/DD')
                //     );
                //     seriesData.push(a.consequence);
                // }
                const myChart = echarts.init(
                    document.getElementById('examLevel')
                );
                myChart.clear();
                // 指定图表的配置项和数据
                // let option = {
                //      title : {
                //         text:row,
                //         x: 'center',
                //     },
                //     xAxis: {
                //         type: 'category',
                //         data: xAxisData
                //     },
                //     yAxis: {
                //         type: 'value'
                //     },
                //     series: [{
                //         data:seriesData,
                //         type: 'line'
                //     }]
                // };
                const option = {
                    title: {
                        text: row,
                        x: 'center',
                    },
                    tooltip: {
                        trigger: 'axis',
                    },
                    toolbox: {
                        show: false,
                        feature: {
                            dataZoom: {
                                yAxisIndex: 'none',
                            },
                            dataView: { readOnly: false },
                            magicType: { type: ['line', 'bar'] },
                            restore: {},
                            saveAsImage: {},
                        },
                    },
                    xAxis: {
                        type: 'category',
                        boundaryGap: false,
                        data: xAxisData,
                    },
                    yAxis: {
                        name: unit,
                        type: 'value',
                    },
                    series: [
                        {
                            name: '数值',
                            type: 'line',
                            data: seriesData,
                            markPoint: {
                                data: [
                                    {
                                        type: 'max',
                                        name: '最大值',
                                    },
                                    {
                                        type: 'min',
                                        name: '最小值',
                                    },
                                ],
                            },
                            markLine: {
                                data: [
                                    {
                                        type: 'average',
                                        name: '平均值',
                                    },
                                ],
                            },
                        },
                    ],
                };
                // 使用刚指定的配置项和数据显示图表。
                myChart.setOption(option);
            }
        },
    },
};
</script>

<style scoped></style>
